/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package libase.web.jsf.bean;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Named;
import libase.entity.Preference;

/**
 *
 * @author aspr0
 */
@Named
@Stateless
public class PreferenceBean extends AbstractBean
{
    private Preference pr = new Preference();

    public Preference getPr()
    {
        if (fetchStrId())
        {
            return pr = em.find(Preference.class, sId);
        }

        return pr;
    }

    public void setPr(Preference pr)
    {
        this.pr = pr;
    }

    public List<Preference> getPreferences()
    {
        return em.createNamedQuery("Preference.findAll").getResultList();
    }

    public Preference getPrByName(String name)
    {
        pr = em.find(Preference.class, name);

        return pr;
    }

    public void create()
    {
        em.persist(pr);
        pr = new Preference();
    }

    public void edit()
    {
        em.merge(pr);
        pr = new Preference();
    }

    public void remove()
    {
        getPr();
        em.remove(pr);
        pr = new Preference();
    }

    public String getOutputDir() throws PreferenceException, IOException
    {
        Preference wrDirPreference = getPrByName("web root directory");

        if (wrDirPreference == null)
        {
            throw new PreferenceException("Set `web root directory` at preferences page.");
        }

        String wrDir = wrDirPreference.getValue();

        if (wrDir == null || wrDir.isEmpty())
        {
            throw new PreferenceException("Set value for `web root directory` at preferences page.");
        }

        if (!(wrDir.endsWith("/") || wrDir.endsWith("\\")))
        {
            throw new PreferenceException("Web root directory path must end with slash. Setup at preferences page.");
        }

        String csvDir = "csv/";
        String outDirFull = wrDir + csvDir;
        File outDirFile = new File(outDirFull);

        if (!outDirFile.exists() && !outDirFile.mkdirs())
        {
            throw new IOException("Please check system write rights for web root or existing files named `csv`.");
        }

        return outDirFull;
    }
}